"use client"

import * as React from "react"
import { usePathname, useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"

interface BiddingTabsProps {
  id: string
}

export function BiddingTabs({ id }: BiddingTabsProps) {
  const pathname = usePathname()
  const router = useRouter()
  
  const tabs = React.useMemo(() => [
    {
      key: "info",
      label: "입찰 기본 정보",
      href: `/evcp/bid/${id}/info`,
    },
    {
      key: "companies",
      label: "입찰 업체",
      href: `/evcp/bid/${id}/companies`,
    },
    {
      key: "items",
      label: "입찰 품목",
      href: `/evcp/bid/${id}/items`,
    },
    {
      key: "schedule",
      label: "입찰 계획",
      href: `/evcp/bid/${id}/schedule`,
    },
  ], [id])

  // 현재 활성 탭 결정
  const activeTab = React.useMemo(() => {
    if (!pathname) return "info"
    
    // pathname에서 lng 부분 제거 (예: /en/evcp/bid/10 -> /evcp/bid/10)
    const normalizedPath = pathname.replace(/^\/[^/]+/, '') || pathname
    
    // 기본 페이지는 info로 처리
    if (normalizedPath === `/evcp/bid/${id}` || normalizedPath.endsWith(`/bid/${id}`)) {
      return "info"
    }
    
    const matchedTab = tabs.find(tab => normalizedPath.includes(`/${tab.key}`))
    return matchedTab?.key || "info"
  }, [pathname, id, tabs])

  return (
    <div className="flex items-center gap-1">
      {tabs.map((tab) => {
        const isActive = activeTab === tab.key
        return (
          <Button
            key={tab.key}
            variant={isActive ? "secondary" : "ghost"}
            size="default"
            className={cn(
              "text-md px-3 py-1 h-7",
              isActive && "bg-secondary"
            )}
            onClick={() => router.push(tab.href)}
          >
            {tab.label}
          </Button>
        )
      })}
    </div>
  )
}

